package com.example.sinoyd.frameapplication.KotlinFrame.Code.UI

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import com.example.sinoyd.frameapplication.KotlinFrame.Code.Adatper.TaskManagerAdapter
import com.example.sinoyd.frameapplication.KotlinFrame.Code.DataClass.Up
import com.example.sinoyd.frameapplication.KotlinFrame.Code.db.FormTask
import com.example.sinoyd.frameapplication.KotlinFrame.Code.db.FormTaskFactor
import com.example.sinoyd.frameapplication.KotlinFrame.Code.jso.JsonFormTask
import com.example.sinoyd.frameapplication.KotlinFrame.Frame.Dataclass.gson
import com.example.sinoyd.frameapplication.KotlinFrame.Frame.Uitl.Networkrequestmodel
import com.example.sinoyd.frameapplication.KotlinFrame.UI.BaseActivity
import com.example.sinoyd.frameapplication.R
import com.example.sinoyd.jiaxingywapplication.Myapplication
import com.sinoyd.Code.Until.Networkrequestaddress
import com.sinoyd.Code.Until.SharedPreferencesFactory
import com.sinoyd.Code.Until.showdialog
import kotlinx.android.synthetic.main.activity_task_management_.*
import okhttp3.Response
import org.xutils.DbManager
import org.xutils.x


/**任务管理**/
class Task_management_Activity : BaseActivity() {
    //数据库
    var myapplication: Myapplication = Myapplication()
    var db: DbManager? = null

    //获取表FormTaks中全部的数据
    var taskList: MutableList<FormTask> = ArrayList()
    var taskListall: MutableList<FormTask> = ArrayList()
    var taskmanageradapter: TaskManagerAdapter? = null

    var myHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    getdata4sqlite()
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_task_management_)
        db = x.getDb(myapplication.getDaoConfig())
        //设置监听
        setlisteners()
    }

    override fun onResume() {
        super.onResume()
        //从数据库取数据
        getdata4sqlite()
    }

    //从数据库取数据
    private fun getdata4sqlite() {
        try {
            taskList = db!!.selector(FormTask::class.java)
                .where("Userid", "=", SharedPreferencesFactory.getdata(this, "RowGuid")).findAll()
            taskListall = db!!.findAll(FormTask::class.java)
            Log.i("scj", "取任务成功")
        } catch (e: Exception) {
            e.printStackTrace()
            Log.i("scj", "取任务失败" + e.message)
        }
        //显示界面
        setview()
    }

    //显示界面
    private fun setview() {
        taskmanageradapter = TaskManagerAdapter(this, taskList)
        lv_task_management.adapter = taskmanageradapter
    }


    override fun requestSuccess(response: Response, TAG: String) {
        super.requestSuccess(response, TAG)
        when (TAG) {
            "postUp" -> {
                try {
                    var up = Up()
                    up = gson.fromJson(responsestr, Up::class.java)

                    if (up.result == "True") {
                        //上传成功，需要更新本地数据库
                        formtask.taskStatusName = "完成"
                        formtask.upload = true
                        try {
                            db!!.update(formtask)
                            Log.i("scj", "本地数据更新成功")
                            val message = Message()
                            message.what = 1
                            myHandler.sendMessage(message)
                        } catch (e: Exception) {
                            e.printStackTrace()
                            Log.i("scj", "本地数据更新失败" + e.message)
                        }
                    }

                    Looper.prepare()
                    Toast.makeText(this, "up.message", Toast.LENGTH_SHORT).show()
                    Looper.loop()

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

        }
    }


    private fun setlisteners() {
        //返回主页
        iv_home.setOnClickListener {
            finish()
        }
    }

    //跳转界面
    fun goto(type: String, guid: String) {
        when (type) {
            "实样比对" -> {
                var intent = Intent(this, New_Realsample_comparison_Activity::class.java)
                intent.putExtra("rowGuid", guid)
                startActivity(intent)
            }
            "水质巡检" -> {
                startActivity(Intent(this, New_Water_Monitoring_Inspection_Activity::class.java))
            }
            "标样核查" -> {
                var intent = Intent(this, New_Standard_solution_verification_Activity::class.java)
                intent.putExtra("rowGuid", guid)
                startActivity(intent)
            }
            "加标回收" -> {
                var intent = Intent(this, New_Standard_Recovery_Activity::class.java)
                intent.putExtra("rowGuid", guid)
                startActivity(intent)
            }
            "性能考核" -> {
                var intent = Intent(this, New_Performance_assessment_Activity::class.java)
                intent.putExtra("rowGuid", guid)
                startActivity(intent)
            }
            else -> {
                Toast.makeText(this, "没有与之匹配的表单[$type]", Toast.LENGTH_SHORT).show()
            }
        }
    }

    //上传任务
    fun upload(type: String, guid: String) {
        var json = when (type) {
            "实样比对" -> {
                getFormTaskJson(guid)
            }
            "水质巡检" -> {
                ""
            }
            "标样核查" -> {
                getFormTaskJson(guid)
            }
            "加标回收" -> {
                ""
            }
            "性能考核" -> {
                ""
            }
            else -> {
                ""
            }
        }

        //发送请求
        showdialog("loadshow")
        var ntrequest = Networkrequestmodel()
        ntrequest.setMethod(Networkrequestmodel.GETREQUEST)
            .settag("postUp")
            .seturl(Networkrequestaddress.URL_Up)
            .addparam("json", json)
            .start(this)

    }

    //实样比对json
    var formtask = FormTask()
    var formtaskfacotr: MutableList<FormTaskFactor> = ArrayList()
    private fun getFormTaskJson(guid: String): String {
        var jso = ""
        try {
            formtask = db!!.selector(FormTask::class.java).where("RowGuid", "=", guid).findFirst()
            formtaskfacotr = formtask.getFormTaskFactor(db!!)
            Log.i("scj", "数据库取任务成功【FormTask】")
        } catch (e: Exception) {
            e.printStackTrace()
            Log.i("scj", "数据库取任务失败【FormTask】" + e.message)
        }

        //为了拼json建的对象
        var jsformtask = JsonFormTask()
        jsformtask.task = formtask
        jsformtask.taskData = formtaskfacotr
        //tostring被重写了
        jso = jsformtask.toString()
        return jso
    }


}
